<?php

/**
 * Description of AutoOpenGraph
 *
 * @version  1.2
 * @version $Rev: 31 $
 * @version $Date: 2012-08-03 11:19:24 +0000 (Fri, 03 Aug 2012) $
 * @version $Id: autoopengraph.php 31 2012-08-03 11:19:24Z webbochsant@gmail.com $
 * @author Daniel Eliasson (joomla at stilero.com)
 * @copyright  (C) 2012-apr-15 Stilero Webdesign http://www.stilero.com
 * @category Plugins
 * @license	GPLv3
 * 
 * Joomla! is free software. This version may have been modified pursuant
 * to the GNU General Public License, and as distributed it includes or
 * is derivative of works licensed under the GNU General Public License or
 * other free or open source software licenses.
 * 
 * This file is part of autoopengraph.
 * 
 * AutoOpenGraph is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * AutoOpenGraph is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with AutoOpenGraph.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */
// no direct access
defined('_JEXEC') or die('Restricted access');

// import library dependencies
jimport('joomla.plugin.plugin');

class plgContentAutoopengraph extends JPlugin {
    var $Article;
    var $classNames;
    var $ogTagsAdded;

    function plgContentAutoopengraph(&$subject, $config) {
        parent::__construct($subject, $config);
        $language = JFactory::getLanguage();
        $language->load('plg_system_autoopengraph', JPATH_ADMINISTRATOR, 'en-GB', true);
        $language->load('plg_system_autoopengraph', JPATH_ADMINISTRATOR, null, true);
        $this->classNames = array(
            'com_article'       =>  'jArticle',
            'com_content'       =>  'jArticle',
            'com_k2'            =>  'k2Article',
            'com_zoo'           =>  'zooArticle',
            'com_virtuemart'    =>  'vmArticle'
        );
    }
    
    /**
     * Method is called by the view
     * 
     * @var string  $context    The context of the content passed to the plugin
     * @var object  $article    content object. Note $article->text is also available
     * @var object  $params     content params
     * @var integer $limitstart The 'page' number
     * @return void
     * @since 1.6
     */        
    public function onContentPrepare($context, &$article, &$params, $limitstart=0){
        //JLoader::register( 'jArticle', dirname(__FILE__).DS.'library'.DS.'jArticle.php');
        if( $context != 'com_content.article' && $context !='com_virtuemart.productdetails'){
            return;
        }
        if(!$this->loadClasses($article)){
            return;
        }
        $this->insertOGTags();        
    }
    
    /**
     * Method is called by the view
     * 
     * @var string  $context    The context of the content passed to the plugin
     * @var object  $article    content object. Note $article->text is also available
     * @var object  $params     content params
     * @var integer $limitstart The 'page' number
     * @return void
     * @since 1.5
     */        
    public function onPrepareContent(&$article, &$params, $limitstart=0){
        if(!$this->loadClasses($article)){
            return;
        }
        $this->insertOGTags();   
    }
    
    public function onK2AfterDisplayContent(& $item, &$params, $limitstart=0){
        if(JRequest::getVar('option')!='com_k2' || JRequest::getVar('view')!='item'){
            return;
        }
        if(!$this->loadClasses($item)){
            return;
        }
        $this->insertOGTags();
    }
    
    private function loadClasses($article){
       $component = JRequest::getVar('option');
        if(array_key_exists($component, $this->classNames)){
            $className = $this->classNames[$component];
            JLoader::register( $className, dirname(__FILE__).DS.'library'.DS.'jArticle.php');
            $articleFactory = new $className($article);
            $this->Article = $articleFactory->getArticleObj();
            return TRUE;
        }
        return false;
   }
   
    private function insertOGTags($articleObj=''){
        if( $this->ogTagsAdded ){
            return;
        }
        if($articleObj==''){
            $articleObj = $this->Article;
        }
        $document = JFactory::getDocument();
        $doctype    = $document->getType();
        if ( $doctype !== 'html' ) { 
            return; 
        }
        $this->addOGTitle($document);
        $this->addOGType($document);
        $this->addOGDesc($document);
        $this->addOGLocale($document);
        $this->addOGSiteName($document);
        $this->addOGImage($document);
        $this->addOGUrl($document);
        $this->addOGExtra($document);
        $this->addOGFBAppID($document);
        $this->ogTagsAdded = true;
    }
    
    private function addOGTitle($document){
        $metaProp = '';
        switch ($this->params->def('og-title')) {
            case 1:
                $metaProp = '<meta property="og:title" content="'.htmlentities(strip_tags( $this->Article->title), ENT_QUOTES, "UTF-8").'" />';
                break;
            case 2:
                $metaProp = '<meta property="og:title" content="'.htmlentities(strip_tags($this->params->def('og-title-custom')), ENT_QUOTES, "UTF-8").'" />';
                break;
            default:
                return;
                break;
        }
        $document->addCustomTag($metaProp);
    }
    
    private function addOGType($document){
        $metaProp = '';
        switch ($this->params->def('og-type')) {
            case 1:
                $metaProp = '<meta property="og:type" content="article" />';
                break;
            case 2:
                $metaProp = '<meta property="og:type" content="website" />';
                break;
            case 3:
                $metaProp = '<meta property="og:type" content="book" />';
                break;
            case 4:
                $metaProp = '<meta property="og:type" content="profile" />';
                break;
            case 5:
                $metaProp = '<meta property="og:type" content="'.$this->params->def('og-type-custom').'" />';
                break;
            default:
                return;
                break;
        }
        $document->addCustomTag($metaProp);
    }
    
    private function addOGDesc($document){
        $metaProp = '';
        switch ($this->params->def('og-desc')) {
            case 1:
                $metaProp = '<meta property="og:description" content="'.htmlentities(strip_tags($this->Article->metadesc), ENT_QUOTES, "UTF-8").'" />';
                break;
            case 2:
                $metaProp = '<meta property="og:description" content="'.htmlentities(strip_tags($this->Article->introtext), ENT_QUOTES, "UTF-8").'" />';
                break;
            case 3:
                $joomlaConfig = JFactory::getConfig();
                $joomlaSiteName = $joomlaConfig->getValue( 'config.MetaDesc' );
                $metaProp = '<meta property="og:description" content="'.htmlentities(strip_tags($joomlaSiteName), ENT_QUOTES, "UTF-8").'" />';
                break;
            case 4:
                $metaProp = '<meta property="og:description" content="'.htmlentities(strip_tags($this->params->def('og-desc-custom')), ENT_QUOTES, "UTF-8").'" />';
                break;
            default:
                return;
                break;
        }
        $document->addCustomTag($metaProp);
    }
    
    private function addOGLocale($document){
        $langObj = JFactory::getLanguage();
        $currentLang = str_replace( "-", "_", $langObj->getTag() );
        switch ($this->params->def('og-locale')) {
            case 1:
                $ogContent = $currentLang;
                break;
            case 2:
                $ogContent = $currentLang;
                break;
            case 3:
                $ogContent = str_replace( "-", "_", $this->params->def('og-locale-custom') );
                break;
            default:
                return;
                break;
        }
        $metaProp = '<meta property="og:locale" content="'.htmlentities(strip_tags($ogContent)).'" />';
        $document->addCustomTag($metaProp);
    }
    
    private function addOGSiteName($document){
        $joomlaConfig = JFactory::getConfig();
        $joomlaSiteName = $joomlaConfig->getValue( 'config.sitename' );
        switch ($this->params->def('og-sitename')) {
            case 1:
                $ogContent = $joomlaSiteName;
                break;
            case 2:
                $ogContent = $this->params->def('og-sitename-custom');
                break;
            default:
                return;
                break;
        }
        $metaProp = '<meta property="og:site_name" content="'.htmlentities(strip_tags($ogContent), ENT_QUOTES, "UTF-8").'" />';
        $document->addCustomTag($metaProp);
    }
    
    private function addOGImage($document){
        $image = $this->ogImage($this->params->def('og-img-prio1'));
        if($image == "" ){
            $image = $this->ogImage($this->params->def('og-img-prio2'));
        }
        if($image == "" ){
            $image = $this->ogImage($this->params->def('og-img-prio3'));
        }
        if($image != ""){
            $metaProp = '<meta property="og:image" content="'.htmlentities(strip_tags($image)).'" />';
            $document->addCustomTag($metaProp);
        }
    }
    
    private function ogImage($option){
        //$images = $this->Article->contentImages;
        switch ($option) {
            case 1:
                //$image = (isset($images[0]['src'])) ? $images[0]['src'] : '';
                $image = (isset($this->Article->firstContentImage)) ? $this->Article->firstContentImage : '';
                break;
            case 2:
                //$image = (isset($this->Article->imageIntro)) ? $this->Article->imageIntro : '';
                $image = (isset($this->Article->introImage)) ? $this->Article->introImage : '';
                break;
            case 3:
                //$image = (isset($this->Article->imageFull)) ? $this->Article->imageFull : '';
                $image = (isset($this->Article->fullTextImage)) ? $this->Article->fullTextImage : '';
                break;
            case 4:
                $images = (!empty($this->Article->imageArray)) ? $this->Article->imageArray : null;
                $cssClass = $this->params->def('og-img-class');
                $classImage = $this->getImageWithClass($images, $cssClass);
                $image = (isset($classImage)) ? $classImage : '';
                break;
            case 5:
                if($this->params->def('og-img-custom') != ''){
                    $image = 'images/'.$this->params->def('og-img-custom');
                }
                break;
            default:
                return;
                break;
        }
        if($image != ""){
            $image = preg_match('/http/', $image)? $image : JURI::root().$image;
            return $image;
        }
    }
    
    private function addOGUrl($document){
        $url = $this->Article->url;
        $metaProp = '<meta property="og:url" content="'.$url.'" />';
        $document->addCustomTag($metaProp);
    }
    
    private function addOGExtra($document){
        $metaProps = array(
            '<meta property="article:published_time" content="'.date('c', strtotime( $this->Article->publish_up) ).'" />',
            '<meta property="article:modified_time" content="'.date('c', strtotime( $this->Article->modified) ).'" />',
            '<meta property="article:section" content="'.htmlentities(strip_tags($this->Article->category_title), ENT_QUOTES, "UTF-8").'" />'
            );
            foreach ($metaProps as $metaProp) {
                $document->addCustomTag($metaProp);
            }
    }
    
    private function addOGFBAppID($document){
        if( $this->params->def('og-fbappid')!="" ){
            $metaProp = '<meta property="fb:app_id" content="'.$this->params->def('og-fbappid').'" />';
            $document->addCustomTag($metaProp);
        }
    }   
    
    private function getImageWithClass($images, $cssClass){
        if( (!isset($images)) || (empty ($images))  ){
            return;
        }
        foreach ($images as $image) {
            if($image['class'] == $cssClass){
                return $image['src'];
            }
        }
    }
}
//End Class